package com.example.hyw.szysteam.arithmetic;

import java.util.ArrayList;

/**
 * Created by HYW on 2018/6/11.
 */

public class Tree {
    Object date;
    Tree left;
    Tree right;
    MyNumber value;

    public Tree(){
    }

    public Tree(Object date,Tree left,Tree right,MyNumber value){
        this.date=date;
        this.left=left;
        this.right=right;
        this.value=value;
    }

    public Object getDate() {
        return date;
    }

    public void setDate(Object date) {
        this.date = date;
    }

    public Tree getLeft() {
        return left;
    }

    public void setLeft(Tree left) {
        this.left = left;
    }

    public Tree getRight() {
        return right;
    }

    public void setRight(Tree right) {
        this.right = right;
    }

    public MyNumber getValue() {
        return value;
    }

    public void setValue(MyNumber value) {
        this.value = value;
    }

    public Tree createTree(ArrayList<Object> rpn){
        Tree tree=null;
        Object object;
        Stacks stacks=new Stacks();
        for(int i=0;i<rpn.size();i++){
            tree=new Tree();
            object=rpn.get(i);
            if(RPN.isOperator(object.toString())){
                Tree t2=(Tree)stacks.top();
                stacks.pop();
                Tree t1=(Tree)stacks.top();
                stacks.pop();
                if(MinTree.maxTree(t1,t2)){
                    tree.setDate(object.toString());
                    tree.setLeft(t1);
                    tree.setRight(t2);
                    tree.setValue(Count.count(object.toString(),t1.getValue(),t2.getValue()));
                    if(tree.getValue().getDenominator()==0){
                        return new Tree("0",null,null,tree.getValue());
                    }
                }else {
                        tree.setDate(object.toString());
                        tree.setLeft(t2);
                        tree.setRight(t1);
                        tree.setValue(Count.count(object.toString(),t1.getValue(),t2.getValue()));
                        if ((tree.getValue().getDenominator()==0)){
                            return new Tree("0",null,null,tree.getValue());
                        }
                    }
                    stacks.push(tree);
                }else {
                tree.setDate(object.toString());
                tree.setValue((MyNumber)object);
                stacks.push(tree);
            }
        }
        return tree;
    }

    public String toString(Tree tree){
        String s="";
        s=outPutTree(tree,s);
        return s;
    }

    public String outPutTree(Tree tree,String s){
        if(tree!=null){
            String s1=outPutTree(tree.getLeft(),s);
            String s2=outPutTree(tree.getRight(),s);
            return s1+s2+tree.getDate();
        }
        return s;
    }
}
